from flask import jsonify, json, Blueprint, request
from flask_restful import Resource, Api
from second_flask.methods import db1
from common.utils.mytoken import myjwt
from common.utils.jwt_token import create_token
from common.utils.myredis import myredis

plant_bp = Blueprint('plant_bp', __name__)

api = Api(plant_bp)


class Register(Resource):
    def post(self):
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        sql = "insert into users(username,password) values('%s','%s')" % (data['username'], data['password'])
        db1.update(sql)
        return jsonify({'code': 200, 'message': '注册成功'})


# 更新缓存
def update_data():
    catelist = myredis.str_get('catelist')
    if catelist:
        sql1 = "select * from cates"
        list1 = db1.find_all(sql1)
        res = xtree(list1)
        myredis.str_set('catelist', json.dumps(res))


class Login(Register):
    def post(self):
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        sql = "select * from users where username='%s' and password='%s'" % (data['username'], data['password'])
        user = db1.find(sql)
        username = user['username']
        user_id = user['id']
        role_id = user['role_id']
        token = create_token(user_id)
        # print('1111111', token)
        return jsonify({'code': 200, 'token': token, 'username': username, 'user_id': user_id, 'role_id': role_id})


class GetCatelist(Resource):
    def get(self):
        # catelist =  myredis.str_get('cateslist')

        catelist = myredis.str_get('catelist')
        if catelist:
            data = json.loads(catelist)
        else:
            print('11111111')
            sql = "select * from cates"
            catelist = db1.find_all(sql)
            data = xtree(catelist)
            myredis.str_set('catelist', json.dumps(data))
        return jsonify({'code': 200, 'catelist': data})


# 无限极分类
def xtree(data):
    if len(data) <= 0:
        return data
    # 对数据解析重组
    tree = {}
    for i in data:
        i['label'] = i['name']
        tree[i['id']] = i
    # 初始化列表
    dlist = []

    for j in data:
        # 查看pid是否为0，为0代表第一级
        pid = j['pid']
        if pid == 0:
            dlist.append(j)
        else:
            # 判断此子类的父类下面是否已经有子类，如果没有初始化
            if 'children' not in tree[pid]:
                tree[pid]['children'] = []
            tree[pid]['children'].append(j)
    return dlist


class AddCate(Resource):
    def post(self):
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        if data['id'] > 0:
            sql = "update cates set name='%s' where id=%d" % (data['catename'], int(data['id']))
            db1.update(sql)
            update_data()
            return jsonify({'code': 201})
        else:
            sql = "insert into cates(name,pid) values('%s',%d)" % (data['catename'], int(data['pid']))
        db1.update(sql)
        update_data()
        return jsonify({'code': 200})


class DelCate(Resource):
    def delete(self):
        id = request.args.get('id')
        sql = "delete from cates where id=%d" % (int(id))
        db1.update(sql)
        update_data()
        return jsonify({'code': '200'})


class Roles(Resource):
    def get(self):
        sql = "select * from role"
        rolelist = db1.find_all(sql)
        return jsonify({'code': 200, 'rolelist': rolelist})


class GetResource(Resource):
    def get(self):
        sql = "select * from resource"
        resource_list = db1.find_all(sql)
        return jsonify({'code': 200, 'resource_list': resource_list})


# 添加角色权限
class AddRoleResource(Resource):
    def post(self):
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        for i in data['re_id']:
            sql = "insert into role_resource values(%d,%d)" % (int(data['role_id']), int(i))
            db1.update(sql)
        return jsonify({'code': 200})


class AddUserRole(Resource):
    def put(self):
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        sql = "update users set role_id=%d where id=%d" % (int(data['role_id']), int(data['id']))
        db1.update(sql)
        return jsonify({'code': 200})


def menu(data):
    if len(data) <= 0:
        return data

    list = []
    idlist = []
    # 遍历取出菜单
    for i in data:
        # 排重
        if i['pid'] not in idlist:
            list.append({'id': i['pid'], 'name': i['pname'], 'son': []})
            idlist.append(i['pid'])

    # 把资源列表放到菜单中
    for index, item in enumerate(list):
        for j in data:
            if item['id'] == j['pid']:
                list[index]['son'].append(j)
    return list


class GetMenu(Resource):
    def get(self):
        data = request.args.get('id')
        # if data:
        #     data = json.loads(data)
        # else:
        #     data = request.form
        #     print('1111111')
        sql = "select  r.id,r.name,r.url,re.id as pid,re.name as pname from role_resource as rr left join resource as r on rr.resource_id=r.id inner join resource as re on r.pid=re.id where rr.role_id=%d" % (
            int(data))
        data = db1.find_all(sql)
        menulist = menu(data)
        return jsonify({'code': 200, 'menulist': menulist})


api.add_resource(Register, '/register', endpoint='register')
api.add_resource(Login, '/to_login', endpoint='to_login')
api.add_resource(GetCatelist, '/getcatelist', endpoint='getcatelist')
api.add_resource(AddCate, '/addcate', endpoint='addcate')
api.add_resource(DelCate, '/delcate', endpoint='delcate')
api.add_resource(Roles, '/getroles', endpoint='getroles')
api.add_resource(GetResource, '/get_resource', endpoint='get_resource')
api.add_resource(AddRoleResource, '/add_role_resource', endpoint='add_role_resource')
api.add_resource(AddUserRole, '/add_user_role', endpoint='add_user_role')
api.add_resource(GetMenu, '/get_menu', endpoint='get_menu')
